package partners

import (
	"encoding/json"
	"gitee.com/theegg/go-brick/app/service/app"
	"gitee.com/theegg/go-brick/app/service/help/credis"
	"github.com/go-redis/redis/v8"
)

var CacheKeyPrefix = TableName + "_"

// @title GetAllPartnersFromCache
// @description 如果缓存不存在　则从数据库取
// @return map[int64]*Partners
func GetAllPartnersFromCache() (map[int64]*Partners, error) {
	redisOp := credis.New()
	key := CacheKeyPrefix + "all"
	data, errGet := redisOp.Get(key)
	if errGet != nil {
		if errGet == redis.Nil {

			data, errDb := GetAllItemsFromDb()
			if errDb != nil {
				return nil, app.NewError(errDb)
			}

			jsonData, _ := json.Marshal(data)

			errSet := redisOp.Set(key, string(jsonData), 0)
			if errSet != nil {
				return nil, errSet
			}

			return data, nil
		}
		panic("Redis-" + errGet.Error())
	}

	var returnData map[int64]*Partners
	jsonErr := json.Unmarshal(data, &returnData)
	if jsonErr != nil {
		return nil, app.NewError(jsonErr)
	}

	return returnData, nil
}
